import type { IDateTimeHeaderOptions } from '@/app/[locale]/admin/home/date-time-header';
import DateTimeHeader from '@/app/[locale]/admin/home/date-time-header';
import { useEffect, useRef, useState } from 'react';
import Chart from '@/lib/chart';
import useToast from '@/hooks/useToast';
import { useQuery } from '@tanstack/react-query';
import { queryNginxLogsWebsiteAccessPercentage } from '@/services/api';
import type { INginxLogsWebsiteAccessPercentage } from '@/interfaces';
import type { ChartData, ChartOptions } from 'chart.js';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import type { TooltipItem } from 'chart.js/dist/types';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';
import classNames from 'classnames';
import Nodata from '@/app/[locale]/common/nodata/nodata';

export default function WebsiteAccessPercentage({
  translatedFields,
}: {
  translatedFields: PrefixedTTranslatedFields<'homeAdminPage'>;
}) {
  const canvas = useRef<HTMLCanvasElement>(null);
  const chartRef = useRef<Chart<'pie', any, any>>();
  const [params, setParams] = useState({
    paths: [],
  });
  const [options, setOptions] = useState<Partial<IDateTimeHeaderOptions>>({
    refreshOptions: {
      isLoading: false,
    },
    configs: {
      hideLeftContent: true,
      showDetails: true,
    },
  });
  const { show } = useToast();
  const [openDetails, setOpenDetails] = useState(false);

  const queryNginxLogsWebsiteAccessPercentageQuery = useQuery(
    ['/nginx', '/logs', '/website', '/access-percentage', params],
    async (context) => {
      return (await queryNginxLogsWebsiteAccessPercentage({
        query: context.queryKey[4] as any,
      })) as INginxLogsWebsiteAccessPercentage;
    },
  );

  useEffect(() => {
    const current = canvas.current;
    const content = queryNginxLogsWebsiteAccessPercentageQuery.data;
    if (current && content) {
      const labels = Object.keys(content.terms);
      const values = Object.values(content.terms);
      const data = {
        labels,
        datasets: [
          {
            label: translatedFields.visitRatio,
            data: values,
          },
        ],
      } as ChartData<'pie'>;
      const options = {
        responsive: true,
        plugins: {
          tooltip: {
            callbacks: {
              label(tooltipItem: TooltipItem<'pie'>) {
                return (
                  translatedFields.visitRatio +
                  ': ' +
                  tooltipItem.formattedValue +
                  '%'
                );
              },
            },
          },
        },
        aspectRatio: 2,
      } as ChartOptions<'pie'>;

      chartRef.current = new Chart(current, {
        type: 'pie',
        data,
        options,
      });
    }

    return () => {
      if (current) {
        chartRef.current?.destroy();
      }
    };
  }, [queryNginxLogsWebsiteAccessPercentageQuery.data]);

  async function onClickRefresh() {
    try {
      setOptions({
        ...options,
        refreshOptions: {
          isLoading: true,
        },
      });

      await queryNginxLogsWebsiteAccessPercentageQuery.refetch();
      show({
        type: 'SUCCESS',
        message: translatedFields.refreshCompleted,
      });
    } catch (e) {
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setOptions({
        ...options,
        refreshOptions: {
          isLoading: false,
        },
      });
    }
  }

  function onClickDetails() {
    setOpenDetails(!openDetails);
  }

  return (
    <div className="card">
      <div className="card-header bg-transparent">
        <DateTimeHeader
          options={{
            clickOptions: {
              onClickRefresh,
              onClickDetails,
            },
            refreshOptions: options.refreshOptions!,
            configs: options.configs!,
          }}
          translatedFields={translatedFields}
        />
      </div>
      <div className="card-body">
        {queryNginxLogsWebsiteAccessPercentageQuery.data && (
          <div>
            <canvas
              className={classNames({
                'd-none': openDetails,
              })}
              ref={canvas}
            ></canvas>

            <>
              {openDetails && (
                <div className="overflow-y-auto" style={{ height: '27.5rem' }}>
                  {Object.keys(
                    queryNginxLogsWebsiteAccessPercentageQuery.data.terms,
                  ).length > 0 ? (
                    <ul className="list-group list-group-flush">
                      {Object.keys(
                        queryNginxLogsWebsiteAccessPercentageQuery.data.terms,
                      ).map((item) => {
                        return (
                          <li
                            key={item}
                            className="list-group-item d-flex justify-content-between align-items-center"
                          >
                            <span>{item}</span>
                            <span className="badge bg-secondary rounded-pill">
                              {
                                queryNginxLogsWebsiteAccessPercentageQuery.data
                                  .terms[item]
                              }
                              %
                            </span>
                          </li>
                        );
                      })}
                    </ul>
                  ) : (
                    <Nodata />
                  )}
                </div>
              )}
            </>
          </div>
        )}

        {queryNginxLogsWebsiteAccessPercentageQuery.isError && (
          <Alert
            message={queryNginxLogsWebsiteAccessPercentageQuery.error}
            type="error"
          />
        )}

        {queryNginxLogsWebsiteAccessPercentageQuery.isLoading && <AlertLoad />}
      </div>
    </div>
  );
}
